package com.stox.client.ui.javafx.chartingy.widget;

import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.effect.DropShadow;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;

import com.stox.client.ui.javafx.chartingy.model.chart.PrimaryChart;
import com.stox.client.ui.javafx.chartingy.model.node.DataNode;
import com.stox.client.ui.javafx.chartingy.model.plot.Data;
import com.stox.client.ui.javafx.core.util.CSS;
import com.stox.client.ui.javafx.core.util.UI;
import com.stox.shared.core.model.Bar;
import com.stox.shared.core.model.Scrip;
import com.stox.shared.core.util.Constant;

public class BarInfoPanel extends HBox implements EventHandler<MouseEvent> {

	private final PrimaryChart primaryChart;
	private final Label open = UI.style(new Label(), CSS.barInfoValueLabel);
	private final Label high = UI.style(new Label(), CSS.barInfoValueLabel);
	private final Label low = UI.style(new Label(), CSS.barInfoValueLabel);
	private final Label close = UI.style(new Label(), CSS.barInfoValueLabel);

	public BarInfoPanel(final PrimaryChart primaryChart) {
		this.primaryChart = primaryChart;
		UI.style(this, CSS.barInfoPanel);
		primaryChart.addEventFilter(MouseEvent.MOUSE_MOVED, this);
		primaryChart.addEventFilter(MouseEvent.MOUSE_DRAGGED, this);
		
		getChildren().addAll(UI.style(new Label("O:"), CSS.barInfoTextLabel), open,
				UI.style(new Label("H:"), CSS.barInfoTextLabel), high,
				UI.style(new Label("L:"), CSS.barInfoTextLabel), low,
				UI.style(new Label("C:"), CSS.barInfoTextLabel), close);
	}

	private Node previousNode;
	DropShadow effect = new DropShadow(30, Color.WHITE);

	@Override
	public void handle(final MouseEvent event) {
		final int index = primaryChart.getDateAxis().getIndexForDisplay(event.getX());
		if ((index > -1) && (index < primaryChart.getPrimaryPlot().getData().size())) {
			final Data<Scrip, Bar> data = primaryChart.getPrimaryPlot().getData().get(index);
			final DataNode<?, ?> dataNode = data.getDataNode();
			if (null != dataNode) {
				if (null != previousNode) {
					previousNode.setEffect(null);
				}
				dataNode.setEffect(effect);
				previousNode = dataNode;
			}
			update(data.getExtraValue());
		}
	}

	public void update(final Bar bar) {
		open.setText(Constant.numberFormat.format(bar.getOpen()));
		high.setText(Constant.numberFormat.format(bar.getHigh()));
		low.setText(Constant.numberFormat.format(bar.getLow()));
		close.setText(Constant.numberFormat.format(bar.getClose()));
	}
}
